<?php
/*
 * kernel/object.dbo.php 
 * 
 * system main arch object, basic initialization
 * 
 * vesrion: 0.0.9.8
 * 
 * Copyright (C) 2010, Taras Kudla
 * 
 */
# checking for php version
if( strcmp("5.2.0",PHP_VERSION)>0 ){
	print "Gepard requires PHP version > 5.2. Your version is: ".PHP_VERSION;
	exit;
}
/*
 * Gepard Version
 */
define("_GEPARD_VERSION","0.0.9.8");
# timezone
define("_GEPARD_TIMEZONE","Europe/Helsinki");
#
define("YES", true); // =)
define("NO", false);
/*
 * Profiler sorting, etc. defines
 */
define("PROFILER_MAX",0);
define("PROFILER_MIN",1);
/*
 * Default user groups
 */
define("_GROUP_ADMIN",1);
define("_GROUP_DEFAULT",2);
/*
 * Run modes defines
 */
define("_AJAX_RUNMODE", 1); # ajax mode, all forms, action, etc. will be prepared for this in automatic mode
define("_HTML_RUNMODE", 0); # using just html, without any dynamic actions by system
define("_CONSOLE_RUNMODE", 2); # just console, usefull for small applications ( for example feed reader by cron, etc.)
/*
 * Access level defines (basic)
 * 
 * You can add any number of levels.
 * 
 * See documentation for more details.
 */
define("_FUNC_USER", 0);
define("_FUNC_ADMIN", 1); 
/*
 * Reaction on errors
 */
define("_STANDARD", 0); # standard reaction for error, nothing serious
define("_PARANOID", 1); # system will stop after any error
/*
 * Environment layer defines
 */
define("_ENV_KERNEL", 0); # kernel running at this moment 
define("_ENV_MOD", 1); # module method called, can use kernel throw api in this case
/*
 * Some useful things
 */
define("_HASH_LENGTH", 20); # hash length for actions
define("_SESSION_NAME", "gppses"); # default session name
define("_ARRAY",0);
define("_STRING",1);
define("_INT",2);
define("_FLOAT",3);
/*
 * Profiler defines
 */
define("_MAX_TIME",0);
define("_MIN_TIME",1);
/*
 * Abstraction layers defines
 */
define("_DEFAULT_ABSTRACT_INIT", "init");
define("_DEFAULT_ABSTRACT_KERNEL", "kernel");
define("_DEFAULT_ABSTRACT_MODULE", "module");
/*
 * Errors types
 */
define("_ERR_USER",10);
define("_ERR_NOTICE",20);
define("_ERR_WARNING",30);
define("_ERR_FATAL",40);
define("_ERR_CRIT",50);
/*
 * Basic log message levels
 */
define("_LOG_MESSAGE", 100); # all messages
define("_LOG_NOTICE", 75); # notice
define("_LOG_ERROR", 50); # errors
define("_LOG_CRITICAL", 25); # fatal errors
/*
 * System modules permission's
 */
define("_PERM_WRITESQL",0); # insert/update/delete system tables
define("_PERM_READSQL",1); # reading from system tables
define("_PERM_WRITE",2); # write to sys files
define("_PERM_ENV",3); # changing environment information
define("_PERM_CALL",4); # call another modules
define("_PERM_CHG",5); # permissions changing
# default modules permissions
define("_PERM_DEFAULT","111111");
/*
 * Basic system signals
 */
define("_SIG_INIT",0); # system start
define("_SIG_DBO",1); # database start
define("_SIG_CACHE",2); # caching engine start
define("_SIG_OPT",3); # system global options load
define("_SIG_ERR",4); # system on error signal
define("_SIG_CRIT",5); # critical system event
define("_SIG_MEM",6); # memory overflow
define("_SIG_ALRM",7); # alarm
define("_SIG_REDIR",8); # http redirect signal
define("_SIG_MSG",9); # system message
define("_SIG_HUP",10); # system stop ( accuracy mode, for ex: redirection )
define("_SIG_CLSCON",11); # closing all alive connection's
# signals for using in modules or in intermodule communication
define("_SIG_USR1",20);	# user defined signal 1
define("_SIG_USR2",21); # user defined signal 2
define("_SIG_USR3",22); # user defined signal 3
define("_SIG_USR4",23); # user defined signal 4
define("_SIG_USR5",24); # user defined signal 5
define("_SIG_USR6",25); # user defined signal 6
define("_SIG_USR7",26); # user defined signal 7
define("_SIG_USR8",27); # user defined signal 8
define("_SIG_USR9",28); # user defined signal 9
define("_SIG_USR10",29); # user defined signal 10
define("_SIG_TERM",255); # system stop

class init
  {
    var $errors = null;
    /*
     * Basic kernel objects
     */
    private $Objects = array(
    "base", "log", "dbo", "options","console", "user", "view", "lang", "file", "api", "session", "tools", "cache","router","encoding");
    private $ObjectsLinks = array(); 	
    /*
     * Basic system startup settings
     */
    private $Workdir = null; # folder where system major files is
    private $Kerneldir = null; # folder where kernel files situated    
	/*
	 * Basic system configuration
	 */  
    private $Configuration = array(
    	# basic url (not required)
    	"url" 		=> null,
    	# url suffix (not required)
    	"urlsuffix"	=> null,
    	# host system signature ( optional )
    	"hostsign"	=> null,
    	# main system run file
    	"runfile"	=> "index",
    	# how to run a system html|ajax|console
    	"runmode"	=> _HTML_RUNMODE,
    	# internal system/applcation name
    	"name"		=>	"appdefault",
    	# basic access level ( can be changed in amin panel) 
    	"accesslevel"	=> _FUNC_USER,
    	# database engine configuration file
    	"dboconf"	=> null,
    	# persistent database connection	
    	"dbopersistent"=>YES,
    	# use dbo data replication, see docs for more information
    	"dbodatareplication"=>NO,
    	# dbo tables prefix
    	"dbotablesprefix"=>null,
    	# caching engine configuration file
    	"cacheconf"	=> null,
    	# logs files directory
    	"logsdir"	=> "app/logs/",
    	# meessage when error generated ( not recomended when using as framework )
    	"messageonerror" => YES,
    	# throw new exception on error
    	"exceptiononerror"=> NO,
    	# directory where backups will store
    	"backupsdir"=>"app/backups/",
    	# where upload files should save
    	"uploadsdir"	=> "app/uploads/",
    	# url to upload files
    	"uploadsurl"=>"app/uploads/",
    	# temporary files directory
    	"tmpdir"=>"app/tmp/",    
    	# timezone
    	"timezone"=>null,
    	# system configuration file ( not required) 
    	"sysappconf"	=> "app/conf/app_default.php",
    	# templates directory in file system
    	"templatesdir"  => "view/templates/",
    	# tempaltes url routine
    	"templatesurl"	=> "view/templates/",
    	# templates engine
    	"tplengine"	=>"native",
    	# modules direcory
    	"modsdir"=>"modules/",    
    	# modules url routine
    	"modsurl"=>"modules/",
    	# library directory
    	"libdir"=>"library/",
    	# lib url
    	"liburl"=>"library/",
    	# url to jscorefiles
    	"jscoreurl"=>"js/",
    	# memory limit, in bytes, by default 10mb
    	"memorylimit"	=> 10485760,
    	# secure mode
    	"secure"	=> _PARANOID,
    	# logging enabled
    	"logtofile"	=> YES,
    	# allow users multi access  ( when one login can work in different sessions )
    	"multiaccess" => true,
    	# system language by default
    	"language"	=> "en",
    	# all supported system languages
    	"syslanguages"=>array("ru","en","ua"),
    	# url style
    	"routermap"	=> "[f].php?[l]&[m]&[a]&[p]",
    	# html,xml,json api file
    	"apifile"	=> "api.php",
    	# basic system encoding, see docs for more details
    	"charset"	=> "utf-8",
    	# session name
    	"sessionname"	=> _SESSION_NAME,
    	# profile enabled, true|false
    	"profiler"  	=> YES,
    	# debug enabled, true|false
    	"debug"		=> YES,
    	# view model by default
    	"viewmodel"	=>"default",
    	# should i connect to cache engine automatically
    	"usecache"	=> NO,
    	# should i connect to database automatically
    	"usedbo"	=> YES,
    	# timeout after site will be available for banned connections
    	"dennytimeout" => 6000
    );  
    private $SystemStartTime = null;
    /*
     * Signals
     */
    private $signals = array();
    /*
     * Library
     */
    private $libloaded = array();
    /*
     * Debugging
     */
    private $DebugBuffer = array(); #
    private $DebugBufferSize = 4096; # size of debugging output buffer (max)
    /*
     * Profiling
     */
    private $Profiler = array();
    private $Profilertime = array();
    /*
     * System options states
     */
    private $optstates = array();
    private $memusage = 0;
    #loaded system objects
    private $Loaded = array();
    private $ENV_LAYER = _ENV_KERNEL;
    private $ENV_CALLER = array(
    "ID" => null,"HASH"=>null, "NAME" => null, "MOD" => null, "MESSAGE" => null,"CALLSTACK"=>array(), "ERROR" => null, "ERROR_COUNT" => 0);
    private $Kernel = _GEPARD_VERSION; # kernel version
    private $Version = _GEPARD_VERSION; # ready content management system version
    /*
     * System Initialization
     */ 
    function __construct()
      {
      	$this->memusage = memory_get_usage();
      	$this->SystemStartTime = microtime(1);
        $this->setsighandler(_SIG_TERM,array(&$this,"stop") );
        $this->Workdir = dirname(__FILE__);
        $this->Kerneldir = $this->parseasdir($this->Workdir);
        $this->Workdir = preg_replace("/(kernel)/", "", $this->Workdir);
        date_default_timezone_set(_GEPARD_TIMEZONE);
        # runmode checking
        if($this->isconsole() ){
        	$this->debug("init","Switching to console runmode");     	
        	$this->set("runmode",_CONSOLE_RUNMODE);
        }
        # runfile detection
        if( isset($_SERVER["SCRIPT_FILENAME"])){
        	$script = $_SERVER["SCRIPT_FILENAME"];
        	$script = str_replace(str_replace("\\","/",$this->Workdir),"",str_replace("\\","/",$script));
        	$script = preg_replace("/(.+)\.([A-z0-9_]{1,6})$/sU","$1",$script);
        	$this->debug("init","Trying to set runfile ($script)...Ok");
        	$this->set("runfile",$script);     	  		
        }
        # loading basic abstract layer and errors handling object
        require_once("abstract.layer.php");
        require_once("object.errors.php");
        $this->errors = new errors($this);           
        # error handler signal
        $this->setsighandler(_SIG_ERR,array(&$this->errors,"create"));
        # message signal handler
        $this->setsighandler(_SIG_MSG,array(&$this->errors,"message"));
        #
        $this->setsighandler(_SIG_CLSCON,array(&$this,"closeallconnections"));
        # alarm signal handler
        $this->setsighandler(_SIG_ALRM,array(&$this->errors,"alarm"));
        /*
         * Seeking for configuration file
         */
		$sysfile = ( defined("_GEPARD_APPCONF"))?_GEPARD_APPCONF:$this->Configuration["sysappconf"];
		# checking for prefix
		if( !preg_match("/^([A-z]{1}\:)/",$sysfile)&& !preg_match("/^(\/{1})/",$sysfile) ){
			$sysfile = $this->Workdir.$sysfile;
		}
		if( is_file($sysfile) ){
			if( preg_match("/\.(php|ini)$/i",$sysfile,$tmp)){
				$filetype = strtolower($tmp[1]);
				if( $filetype=="php"){
					$Gepard = & $this;
					require_once($sysfile);					
				} else {
					# parsing as ini file
					$data = parse_ini_file($sysfile,true);
					//$this->htmlvardump($data);
					# system parameters
					if( array_key_exists("system",$data) && is_array($data["system"])){
						foreach($data["system"] as $k=>$v){
							if( array_key_exists($k,$this->Configuration)){
								$this->Configuration[$k]=$v;
							}
						}
					}
					# database
					if( array_key_exists("database",$data) && is_array($data["database"])){
						foreach($data["database"] as $k=>$v){
							if( !is_array($v)) continue;
							$this->Configuration["dboconf"][$k]=$v;
						}
					}
				}
			} else{
				$this->error("init","Cannot detect system configuration file type, it must be: .php or .ini");
			}

		} else {
			$this->Debug("INIT","System configuration file not found");
		}           
        /*
         * Setting major system start signal
         */
		$this->setsighandler(_SIG_INIT,array(&$this,"start"));	
		$this->profiler("INIT","System construction completed ",$this->SystemStartTime);
      }
	
    function __destruct(){    	
    	$this->signal(_SIG_TERM);
    }
    
	# dynamic linking improvement method
	function __get($key){
		# checking to prevent code execution in configuration file
		if( !$this->sighandler(_SIG_INIT))
			return false;
		# object is not at allowed list
		if (!in_array($key, $this->Objects) ){
			$this->error("INIT","Property '$key' not found");
		return false;
		}
		$start = microtime(true);
		# object already was loaded
		if($this->isloaded($key)) {
			# checking if module action running, adding to it's callstack 
			if( $this->ENV_LAYER==_ENV_MOD)
				$this->ENV_CALLER["CALLSTACK"][]="kernel.".$key;	    	
		return $this->ObjectsLinks[$key];
		}
		$file = $this->Kerneldir."object.".$key.".php";
		if( file_exists($file)){
			require($file);	
		} else {
			print $file;
			$this->error("INIT","System object '$key' file not found");
			return null;
		}
		if (get_parent_class($key) == _DEFAULT_ABSTRACT_KERNEL){
			$tmpObj = new $key($this);
			$tmpObj->init();
			$this->ObjectsLinks[$key] = &$tmpObj;
		}
		$this->Loaded[] = $key;
		$this->profiler("OBJECT LOADER", "Kernel object '" . $key . "' loaded",$start);            
		return $this->ObjectsLinks[$key];
	}

/*
 * Basic system start method ( or by signal _SIG_INIT) 
 */      
    public function start()
      {
      	if( $this->sigcalled(_SIG_INIT)){
      		return false;
      	}
      	if($this->isconsole() ){     	
        	$this->set("runmode",_CONSOLE_RUNMODE);
        }
        $StartPoint = microtime(1);
        preg_match("/^(?:(http|https):\/\/)?([^\/]+)(.*)/i", $this->get("url"), $tmp);
        $this->UrlSuffix = isset($tmp[3]) ? $tmp[3] : "/";
        $totalInitTime = round((microtime(1) - $StartPoint), 4);
        $this->signals[_SIG_INIT]["called"] = true;
        
        # Database engine start
        if ( $this->Configuration["usedbo"] ){
        	$this->dbo->connect();
        }       
        # Cache engine start
        if ($this->Configuration["usecache"] )
          {
            $this->cache->connect();
          }
	$this->profiler("INIT","System initialization",$StartPoint);
        
      }
/*
 * String data encoding to unrecognized format
 */
      
    public function encodeString($str)
      {
        $str = md5($str);
        $salt = substr($str, 5, 9);
        $str = substr(md5($salt), 5, 2) . "|" . $str . "|" . substr(md5($salt), 0, 5);
        return strtoupper($str);
      }    
/*
 * Strings filtering
 */

    public function escapeString($var,$allowed=null){
    	/**
    	 * 
    	 */
        $replaces = array(">"=>"&gt;","<"=>"&lt;",'\"'=>"&quot;","\""=>"&quot;","\'"=>"&#039;","'"=>"&#039;","{"=>"&#123;","}"=>"&#125;");        
        if( is_array($allowed)){
        	foreach($allowed as $k=>$v){
        		if(array_key_exists($v,$replaces))unset($replaces[$v]);
			}
		}
        $var = str_replace(array_keys($replaces),array_values($replaces),$var);
      	return $var;
      }

    public function escapePOST()
      {
        $a = array();
        foreach (func_get_args() as $k => $v)
          {
            $a[] = $this->escapeString($_POST[$v]);
          }
        return $a;
      }

    public function escapeList()
      {
        $a = array();
        foreach (func_get_args() as $k => $v)
          {
            $a[] = $this->escapeString($v);
          }
        return $a;
      }

/*
 * Library methods 
 */
    public function libload($name,$parameters=null){
        $file=$this->parseasdir($this->get("libdir"))."lib.".$name.".php";
        if(file_exists($file)){
            require_once($file);
            if( class_exists($name,false) ){
            	if(get_parent_class($name)=="library"){
            		$libobj = new $name($this);
            		# checking for input parameters            		
            		if( !is_array($parameters))
            			$parameters=array();
            		call_user_func_array(array(&$libobj,"init"),$parameters);
            		$libobj->init();
            		return $libobj;
            	}
            } else {
            	$this->error("LIB LOADER","Cannot found class '$name' in library file.");
            }
            $this->libloaded[]=$name;        
        }
    }
    
    public function islibloaded($name){
    	return in_array($name,$this->libloaded);
    }
    
    public function libexists($name){
    	$file=$this->parseasdir($this->get("libdir"))."lib.".$name.".php";
    	return file_exists($file);
    }
/*
 * Signals handling ( very simple version )
 */    
	
    # sets handler for signal, $handler - array, for example: array(&$object,$methodname) 
    public function setsighandler($signo,$handler){
    	
    	# check
    	if( $this->ENV_LAYER==_ENV_MOD && ( $signo<20 || $signo>30 ) ){
    		$this->error("INIT","Signal '$signo' is reserved for system handler, non module");		
    		return false;
    	} else if( isset($this->signals[$signo]) ){
    		$this->error("INIT","Signal '$signo' have a handler already");
    		return false;
    	} else if ( !is_array($handler) || !is_object($handler[0]) ){
    		$this->error("INIT","Signal '$signo' handler definition is incorrect");
    		return false;    		
    	} 
    	$this->signals[$signo] = array("handler"=>$handler,"called"=>false);
    	$this->Debug("INIT","Handler for signal '$signo' ");
    	return true;
    }
    
    # invoking signal handler
    public function signal( $signo,$parameters = array() ){
        if( !isset($this->signals[$signo]) ){
    		$this->error("INIT","Cannot fing handler for a signal '$signo' ");
    		return false;
    	}
    	list($class,$method) = $this->signals[$signo]["handler"];
    	call_user_func_array(array(&$class,$method),$parameters);
    	$this->signals[$signo]["called"]=true;    	   	
    }
    
    # checking if it was called
    public function sigcalled( $signo ){
    	return isset($this->signals[$signo])?$this->signals[$signo]["called"]:false;
    }
    # checking if signal has a handler
    public function sighandler($signo){
    	return array_key_exists($signo,$this->signals);
    }
/*
 * Global Data Checking 
 */
    public function checkPOST() // requires post variable names, for ex. checkPOST("name","fullname",...);
      {
        foreach (func_get_args() as $k => $v)
          {
            if (!isset($_POST[$v]))
                return false;
          }
        return true;
      }

    public function checkGET() // requires get variable names, for ex. checkGET("name","fullname",...);
      {
        foreach (func_get_args() as $k => $v)
          {
            if (!isset($_GET[$v]))
                return false;
          }
        return true;
      }
/*
 * Debugging 
 */
    public function Debug($object, $string = null)
      {
      	if( $this->Configuration["debug"] )
        $this->DebugBuffer[] = array( $object,$string );
        return true;
      }
   
    public function &GetDebug($return=_ARRAY)
      {
      	if( $return == _STRING){
      		$buf = null;
      		foreach( $this->DebugBuffer as $k=>&$v){
      			$buf.=join(" | ",$v)."\n";}
      		return $buf;
      	}      
        return $this->DebugBuffer;
      }
      
/*
 * Profiling
 */     
     public function profiler($source,$string=null,$starttime=1){
     	if($this->Configuration["profiler"]){
     		$envline = ($this->ENV_LAYER==_ENV_KERNEL?"kernel":$this->ENV_CALLER["MOD"]."-".$this->ENV_CALLER["NAME"]);
     		$time=round(microtime(1)-$starttime,4);
     		$id = "call".count($this->Profiler);
     		$this->Profiler[$id]=array(strtolower($source),$string,$envline,$time);
     		$this->Profilertime[$id]=$time;
     		# checking if debug enabled
     		if($this->Configuration["debug"]) $this->debug($source,"Profiler call: ".$string);
     		return true;
     	}
     }
     
     public function GetProfiler(){
     	return $this->Profiler;
     }
/*
 * System options states
 */
	public function setstate($key,$state){
		if( array_key_exists($key,$this->Configuration)){
			$current = $this->Configuration[$key];
			# trying to set new state
			$this->set($key,$state);
			# trying to save old state
			$this->optstates[$key]=$current;
		}
	}
	public function restorestate($key){
		if( array_key_exists($key,$this->optstates)){
			$oldstate = $this->optstates[$key];
			$this->set($key,$oldstate);
		}
	}
/*
 * System options set, get methods
 */      

      public function set($key,$value=null){
      	if( !in_array($key,$this->Configuration) ){
      		$this->error("INIT","System parameter '$key' not found");
      		return false;
      	}
      	$key = strtolower($key);
    	# specific for language
    	if( $key == "language" || $key=="runmode" || $key=="exceptiononerror"){
    		$this->Configuration[$key]=$value;
    		return false;
    	}
    	if( $this->sigcalled(_SIG_INIT) ){
    		$this->error("INIT","Cannot set system parameters ('$key') after signal _SIG_INIT(init->start method)");
    		return false;
    	}
    	# all options, cannot be changed after _SIG_INIT
    	if( array_key_exists($key,$this->Configuration)){
    		$this->Configuration[$key] = $value;
    	}
    	return true;
    }
    
    public function get($key){
    	if( ($key=="dboconf" || $key=="cacheconf") && $this->ENV_LAYER==_ENV_MOD && $this->ENV_CALLER["MOD"]!="sys" ){
    		$this->error("INIT","Cannot return dbo or cache parameters when module action is running");
    	}    	
    	# getting system parameters
    	if( array_key_exists($key,$this->Configuration) ){
    		return $this->Configuration[$key];
    	}
    	return false;
    }
/*
 * Some usefull methods
 */      
    public function runtimepoint(){
    	
    	return round( (microtime(true)-$this->SystemStartTime) ,4);    	
    }

    public function envclear(){
    	$this->ENV_LAYER = _ENV_KERNEL;
    	$this->ENV_CALLER["ID"] 		 = null;
    	$this->ENV_CALLER["HASH"]		 = null;
    	$this->ENV_CALLER["NAME"] 		 = null;
    	$this->ENV_CALLER["MOD"] 		 = null;
    	$this->ENV_CALLER["MESSAGE"] 	 = null;
    	$this->ENV_CALLER["ERROR"] 		 = null;
    	$this->ENV_CALLER["ERROR_COUNT"] = 0;
    	$this->ENV_CALLER["CALLSTACK"] 	 = array();
    	return true;
    } 
    
    public function setenvlayer($layerno){
    	
    	$this->ENV_LAYER = $layerno;
    	return true;
    }
    
    public function setenvcaller(array $callerdata){
    	$this->ENV_CALLER = $callerdata;
    }
    
    public function updateenvcaller($key,$value=null){
    	$key=strtoupper($key);
    	if( array_key_exists($key,$this->ENV_CALLER)){
    		$this->ENV_CALLER[$key] = $value;
    	}
    	return true;
    }
    
    public function getenvlayer(){
    	
    	return $this->ENV_LAYER;	
    }
    
    public function getenvcaller($key=null){
    	
    	if($key!=null && array_key_exists(strtoupper($key),$this->ENV_CALLER) ){
    		return $this->ENV_CALLER[strtoupper($key)];
    	}
    	return $this->ENV_CALLER;
    }
    
    public function path(){
    	return $this->Workdir;
    }
    
    public function corepath(){
    	return $this->Kerneldir;
    }
    
    public function kernelpath(){
    	return $this->Kerneldir;
    }
    
    public function apifile(){
    	return $this->Configuration["apifile"];
    }
    
    public function url(){
    	return $this->Configuration["url"];
    }

    public function GetViewModel(){

    	return $this->Configuration["viewmodel"];
    }
    public function viewmodel(){
    	return $this->Configuration["viewmodel"];
    }
    
    public function GetMemoryUsage(){
    	return memory_get_usage();
    }
    public function memusage(){
    	return memory_get_usage();    
    }
    
    public function GetLanguage(){
    
    	return $this->Configuration["language"];
    }
    public function language(){
    	return $this->Configuration["language"];
    }
    
    public function GetSysLanguages(){
    	
    	return $this->Configuration["syslanguages"];
    }
    public function syslanguages(){
    
   	 return $this->Configuration["syslanguages"];
    }
    public function runmode(){
    	return $this->Configuration["runmode"];
    }
    
    public function GetRouterMap(){
    	
    	return $this->Configuration["routermap"];
    }
    
    public function accesslevel(){
    	return $this->Configuration["accesslevel"];	
    }    
    
    public function routermap(){
    	return $this->Configuration["routermap"];
    }

    public function GetUserAccessLevel(){
    	
    	return $this->Configuration["accesslevel"];
    }
    public function useraccesslevel(){
    	return $this->Configuration["accesslevel"];
    }
    
    public function setLanguage($language){
    	if(!in_array($language,$this->SysLanguages) ){
    		$this->error("INIT","Language '$language' is unsupported.");
    		return false;
    	} else $this->set("language",$language);
    	return true;
    }
    
    public function GetCharset(){
    	
    	return $this->Configuration["charset"];    
    }
    public function charset(){
    	return $this->Configuration["charset"];    
    }
    
    public function GetVersion(){
    	return $this->Version;
    }
    
    
    public function GetKernelVersion(){
    	return $this->Kernel;
    }
    
    public function GetUrl(){
    	return $this->Url;
    }
    
    public function isloaded($objname){
    	return @in_array($objname,$this->Loaded);   	
    }
    
    # parse configuration option as file
    public function parseconfasfile($key){
    	$val=$this->get($key);
		if( !preg_match("/^([A-z]{1}\:)/",$val)&& !preg_match("/^(\/{1})/",$val) ){
			$val = $this->Workdir.$val;
		}
		return $val;
    }
    # parse dir or file to system path
    public function parsepathtosys($val){
		if( !preg_match("/^([A-z]{1}\:)/",$val)&& !preg_match("/^(\/{1})/",$val) ){
			$val = $this->Workdir.$val;
		}
		return $val;
    }
    # parse as dir ( check if end / present, etc )
    public function parseasdir($val){
    	$val = $this->parsepathtosys($val);
    	$ch=$val[strlen($val)-1];
    	if( $ch=="/" || $ch=="\\" )
    	return $val;
    	else 
    	return $val."/";
    }
    # parse as url
    public function parseasurl($val){
    	if( !preg_match("/^(http|https|\.\.|\.|\/)/",$val)){
    		$val = $this->get("url").$val;
    	}
    	$ch=$val[strlen($val)-1];
    	if( $ch=="/" || $ch=="\\" )
    	return $val;
    	else 
    	return $val."/";
    }    
    
/*
 * Html var_dump implementation
 */    
    public function htmlvardump(&$var){
    	print "<pre>Html dump of variable :\n";
    	print_r($var);
    	print "</pre>";
    }
/*
 * Messaging, redirecting && simple errors
 */ 
    public function message($message){
    	return $this->errors->message($message);
    }   
    
    public function error($source,$description=null,$type=_ERR_USER){
    	return $this->errors->create($source,$description,$type,null,null);
    }
    
    public function redirect($alias=null,$params=null){
    	$this->base->sendHeader($alias,$params);
    }
    
/*
 * System stopping
 */
    
    # closing all alive connections
    public function closeallconnections(){
		if($this->isloaded("session"))
			$this->session->SessionClose();
		if($this->isloaded("cache"))
			$this->cache->disconnect();	
		if($this->isloaded("dbo"))
			$this->dbo->disconnect();
	}
    
    public function stop(){
    	if( $this->sigcalled(_SIG_TERM))
    		return false;
    	if( !$this->sigcalled(_SIG_CLSCON))
			$this->signal(_SIG_CLSCON);
		$this->Debug("LAST","System stopped.");
		exit;
    }
/*
 *  Evaluating global PHP Environmnet and os parameters for Gepard
 */
    public function evaluate(){
    	
    	$message = null;
    	$result  = true;
    	if(!isset($_SERVER["REQUEST_URI"])){
    		$message = "\$_SERVER[REQUEST_URL] required (not neccessary)";	
    	}
    	if( !isset($_COOKIE)){
    		$message = "\$_COOKIE required (not neccessary)";
    		$result  = false;
    	}   	
    	if ( !extension_loaded("gd") ){
    		$message = "PHP extension \"gd\" required";
    		$result  = false;
    	}
    	if ( !extension_loaded("zlib")){
    		$message = "PHP extension \"zlib\" required";
    		$result  = false;
    	}
    	if ( !extension_loaded("mbstring")){
    		$message = "PHP extension \"mbstring\" required";
    		$result	 = false;
    	}
    	if( !is_writable($this->GetConfigurationFile("logs"))){
    		$message = "Logs directory should be writable";
    		$result	 = false;
    	}
    	return array($message,$result);
    }    
/*
 * Detect if i'm running in console ( without web server )
 */
    public function isconsole(){
    	
    	return (strcmp(strtolower(substr(PHP_SAPI,0,3)),"cli")==0)?true:false;
    }
  }
  /*
   * System initialization
   */
  $Gepard = new init();
?>
